<?php


$config["timer"][]="WeatherTimer";

function WeatherTimer(){
	global $config;	

	if (time()>$config["WeatherCollectionTimer"]){
		//send xget data
		WeatherImport();
		// set next collecting in 30 minutes
		$config["WeatherCollectionTimer"]=time()+(30*60);
		//a xAP send happens on collection so make the next send 15 minutes
		$config["WeatherSendTimer"]=time()+(15*60);
	}
	if (time()>$config["WeatherSendTimer"]){
		WeatherxAPSendAll();
		$config["WeatherSendTimer"]=time()+(15*60);
	}

	
}

function WeatherImport($id=0){
$results=dbquery("select SourceID,Source,SourceRef,SourceType,Active,Forecast from xAP_Weather_Source");

foreach($results as $row){	
	if($row["Active"]==1 && ($id==0 || $id==$row["SourceID"])){
		if($row["Source"]=="BBC"){
			WeatherImportChannelBBC("http://feeds.bbc.co.uk/weather/feeds/rss/obs/".$row["SourceType"]."/".$row["SourceRef"].".xml",$row["SourceID"]);
			if($row["Forecast"]==1){
				WeatherImportChannelForeCastBBC("http://feeds.bbc.co.uk/weather/feeds/rss/5day/".$row["SourceType"]."/".$row["SourceRef"].".xml",$row["SourceID"]);
			}
			// send xAP
			WeatherxAPSend($row["SourceID"]);
		}
	}
}

}
function WeatherxAPSendAll(){
	$results=dbquery("select SourceID,Active from xAP_Weather_Source");

	foreach($results as $row){	
		if($row["Active"]==1){
				WeatherxAPSend($row["SourceID"]);
		}
	}

}

function WeatherImportChannelBBC($url,$id){
	global $config;	
	xAPLog("Import","Collecting ".$url,"");
	//get data
	$xmldata=file_get_contents($url);
	$xmldata=utf8_encode($xmldata);
	$p = xml_parser_create('UTF-8');
	xml_parser_set_option($p,XML_OPTION_TARGET_ENCODING, "UTF-8");
	xml_parser_set_option($p,XML_OPTION_SKIP_WHITE,1);
	xml_parse_into_struct($p, $xmldata, $vals);
	xml_parser_free($p);
	xAPLog("Import","Collected ".$url,"");
	
	
	//parse
	$ischannel=0;
	$isitem=0;
	$p=0;

		foreach($vals as $key=>$value){

		if($value["tag"]=="CHANNEL" && $value["type"]=="open" && $ischannel==0){
			$ischannel=1;
			$channel=array();
		}
		if($value["tag"]=="CHANNEL" && $value["type"]=="close" && $ischannel==1){
			$ischannel=0;
			@WeatherSaveChannel($channel,$id);
			$channel=array();
		}
		if($value["tag"]=="TITLE" && $value["type"]=="complete"  && $ischannel==1 && $isitem==0){
			$channel["location"]=$value["value"];
			if(strpos($channel["location"],"Observations for ")>0){
				$channel["location"]=trim(substr($channel["location"],strpos($channel["location"],"Observations for ")+17));
			}
		}

		
		
		if($value["tag"]=="ITEM" && $value["type"]=="open" && $isitem==0){
			$isitem=1;
		}
		if($value["tag"]=="TITLE" && $value["type"]=="complete" && $isitem==1){
			$channel["icon"]=$value["value"];
			if(strpos($channel["icon"],":")>0){
				
				$channel["icon"]=trim(substr($channel["icon"],strpos($channel["icon"],":")+1));
				if(strpos($channel["icon"],".")>0){
					$channel["icon"]=trim(substr($channel["icon"],0,strpos($channel["icon"],".")));
					$channel["icon"]=CheckIcon($channel["icon"]);
				}
			}
		}
		if($value["tag"]=="DESCRIPTION" && $value["type"]=="complete" && $isitem==1){
			$t=explode(",",$value["value"]);
			foreach($t as $v){
				$e=explode(":",trim($v));
				//strip clean and fix
				$e[0]=str_replace(" ","",strtolower($e[0]));
				$e[1]=htmlentities(utf8_decode($e[1]));
				$e[1]=str_replace("mph","",$e[1]);
				$e[1]=str_replace("%","",$e[1]);
				$e[1]=str_replace("mB","",$e[1]);
				//chop off extra data
				if(strpos($e[1],"&")>0){
					$e[1]=trim(substr($e[1],0,strpos($e[1],"&")));
				}
				// save and trim
				$channel[$e[0]]=trim($e[1]);
			}
		}
		
		if($value["tag"]=="GEO:LAT" && $value["type"]=="complete" && $isitem==1){
			$channel["lat"]=$value["value"];
		}
		if($value["tag"]=="GEO:LONG" && $value["type"]=="complete" && $isitem==1){
			$channel["lng"]=$value["value"];
		}
		if($value["tag"]=="PUBDATE" && $value["type"]=="complete" && $isitem==1){
			$channel["datestamp"]=$value["value"];
		}
		$i++;
	}

$vals=array();
xAPLog("Import","Processed ".$url,"");
}


function WeatherSaveChannel($channel,$id){
// see if there has bneen a change
	$r=dbquery("select DateStamp,Source from xAP_Weather_Source where SourceID=".$id);
	if($r[0]["DateStamp"]==$channel["datestamp"] || $channel["datestamp"]==""){
		//no change so no log and no save
		xAPLog("Import","No change in date stamp of report. Ignoring",$r[0]["DateStamp"]."-".$channel["datestamp"]); 
		return;
	}
	
// move current data into log
	$sql="
	insert into xAP_Weather_Log
	(SourceId,DateStamp,Icon,Temp,WindSpeed,WindDirection,Humidity,Pressure,Visibility)
	
	select
	SourceId,DateStamp,Icon,Temp,WindSpeed,WindDirection,Humidity,Pressure,Visibility
	from xAP_Weather_Source where SourceID=$id
	
	";
	dbexec($sql);
	xAPLog("Import",$sql,"");
	$sql="update xAP_Weather_Source set
	Lat='".dbesc($channel["lat"])."',
	Lng='".dbesc($channel["lng"])."',
	Location='".dbesc($channel["location"])."',
	Icon='".dbesc($channel["icon"])."',
	Temp='".dbesc($channel["temperature"])."',
	DateStamp='".dbesc($channel["datestamp"])."',
	WindSpeed='".dbesc($channel["windspeed"])."',
	WindDirection='".dbesc($channel["winddirection"])."',
	Humidity='".dbesc($channel["relativehumidity"])."',
	Pressure='".dbesc($channel["pressure"])."',
	Visibility='".dbesc($channel["visibility"])."'
	
	where SourceID=".$id;
	dbexec($sql);
	xAPLog("Import",$sql,"");
//Event
	if ($r[0]["Source"]!=""){	
		EventRunBySource("Weather","Current Weather Change ".$r[0]["Source"],$channel,"Triggered when the current conditions have changed");
	}
EventRunBySource("Weather","Current Weather Change",$channel,"Triggered when the current conditions have changed");
}

function WeatherImportChannelForeCastBBC($url,$id){
	global $config;	
	xAPLog("Import","Forecast Collecting ".$url,"");
	//get data
	$xmldata=file_get_contents($url);
	$xmldata=utf8_encode($xmldata);
	$p = xml_parser_create('UTF-8');
	xml_parser_set_option($p,XML_OPTION_TARGET_ENCODING, "UTF-8");
	xml_parser_set_option($p,XML_OPTION_SKIP_WHITE,1);
	xml_parse_into_struct($p, $xmldata, $vals);
	xml_parser_free($p);
	xAPLog("Import","Forecast Collected ".$url,"");
	
	//print_r($vals);
	//parse
	$ischannel=0;
	$isitem=0;
	$p=0;
	$i=0;

		foreach($vals as $key=>$value){
		
		if($value["tag"]=="CHANNEL" && $value["type"]=="open" && $ischannel==0){
			$ischannel=1;
			$channel=array();
		}
		if($value["tag"]=="CHANNEL" && $value["type"]=="close" && $ischannel==1){
			$ischannel=0;
			@WeatherSaveForecast($channel,$item,$id);
			$channel=array();
		}
		if($value["tag"]=="TITLE" && $value["type"]=="complete"  && $ischannel==1 && $isitem==0){
			$channel["location"]=$value["value"];
			if(strpos($channel["location"],"Forecast for ")>0){
				$channel["location"]=trim(substr($channel["location"],strpos($channel["location"],"Forecast for ")+13));
				
			}
		}

		
		
		if($value["tag"]=="ITEM" && $value["type"]=="open" && $isitem==0){
			$isitem=1;
		}
		if($value["tag"]=="ITEM" && $value["type"]=="close" && $isitem==1){
			$isitem=0;
			$i++;
		}
		if($value["tag"]=="TITLE" && $value["type"]=="complete" && $isitem==1){
			$item[$i]["icon"]=$value["value"];
			if(strpos($item[$i]["icon"],":")>0){
			
			    $item[$i]["dayname"]=trim(substr($item[$i]["icon"],0,strpos($item[$i]["icon"],":"))); 
				$item[$i]["icon"]=trim(substr($item[$i]["icon"],strpos($item[$i]["icon"],":")+1));
				
				if(strpos($item[$i]["icon"],",")>0){
					$item[$i]["icon"]=trim(substr($item[$i]["icon"],0,strpos($item[$i]["icon"],",")));
					$item[$i]["icon"]=CheckIcon($item[$i]["icon"]);
				}
			}
		}
		if($value["tag"]=="DESCRIPTION" && $value["type"]=="complete" && $isitem==1){
			$t=explode(",",$value["value"]);
			foreach($t as $v){
				$e=explode(":",trim($v));
				//strip clean and fix
				$e[0]=str_replace(" ","",strtolower($e[0]));
				$e[1]=htmlentities(utf8_decode($e[1]));
				$e[1]=str_replace("mph","",$e[1]);
				$e[1]=str_replace("%","",$e[1]);
				$e[1]=str_replace("mB","",$e[1]);
				//chop off extra data
				if(strpos($e[1],"&")>0){
					$e[1]=trim(substr($e[1],0,strpos($e[1],"&")));
				}
				// save and trim
				$item[$i][$e[0]]=trim($e[1]);
			}
		}
		
		if($value["tag"]=="GEO:LAT" && $value["type"]=="complete" && $isitem==1){
			$item[$i]["lat"]=$value["value"];
		}
		if($value["tag"]=="GEO:LONG" && $value["type"]=="complete" && $isitem==1){
			$item[$i]["lng"]=$value["value"];
		}
		if($value["tag"]=="PUBDATE" && $value["type"]=="complete" && $isitem==1){
			$item[$i]["datestamp"]=$value["value"];
		}
	}

$vals=array();
xAPLog("Import","Forecast Processed ".$url,"");
}
function WeatherSaveForecast($channel,$item,$id){

// see if there has bneen a change
	$r=dbquery("select DateStamp from xAP_Weather_Forecast where SourceID=".$id);
	if($r[0]["SourceDateStamp"]==$item[0]["datestamp"] || $item[0]["datestamp"]==""){
		//no change so no log and no save
		xAPLog("Import","No change in date stamp of report. Ignoring",$r[0]["DateStamp"]."-".$item[0]["datestamp"]); 
		return;
	}
	
// move current data into log
	dbexec("delete  from xAP_Weather_Forecast where SourceID=".$id); 
foreach($item as $v){
	$sql="insert into xAP_Weather_Forecast 
	(SourceID,SourceDateStamp,DateStamp,DayName,Icon,TempMin,TempMax,WindSpeed,WindDirection,Humidity,Pressure,Visibility,Pollution,UV) VALUES (
'".$id."',
'".dbesc($v["datestamp"])."',
'".dbesc($v["datestamp"])."',
'".dbesc($v["dayname"])."',
'".dbesc($v["icon"])."',
'".dbesc($v["mintemp"])."',
'".dbesc($v["maxtemp"])."',
'".dbesc($v["windspeed"])."',
'".dbesc($v["winddirection"])."',
'".dbesc($v["humidity"])."',
'".dbesc($v["pressure"])."',
'".dbesc($v["visibility"])."',
'".dbesc($v["pollution"])."',
'".dbesc($v["uvrisk"])."')
";
	dbexec($sql);

	}
//Event
EventRunBySource("Weather","Forecast Weather Change",$item,"Triggered when the forecast has changed");

}


function WeatherxAPSend($id){
xAPLog("xAP","Sending routine xAP",""); 



$sql="select * from xAP_Weather_Source where SourceID=$id";
$results=dbquery($sql);
$row=$results[0];
if ($row["Active"]==1){
	$sunrise=date_sunrise(date("H:i"),SUNFUNCS_RET_STRING,$row["lat"],$row["lng"]);
	$sunset=date_sunset(date("H:i"),SUNFUNCS_RET_STRING,$row["lat"],$row["lng"]);
	$now=date("H:i:s");
	//day or night
	$timeofday="night";
	if(strtotime($sunrise)<strtotime($now) && strtotime($sunset)>strtotime($now)){
			$timeofday="day";
	}	
	
	
	$msg="Weather.Report\n";
	$msg.="{\n";
	$msg.="UTC=".date("H:i",strtotime($row["DateStamp"]))."\n";
	$msg.="DATE=".date("Ynd",strtotime($row["DateStamp"]))."\n";
	$msg.="WindM=".$row["WindSpeed"]."\n";
	$msg.="WindK=".intval(($row["WindSpeed"]/1.6))."\n";
	$msg.="WindDirC=".$row["WindDirection"]."\n";
	$msg.="TempC=".$row["Temp"]."\n";
	$msg.="TempF=".intval(($row["Temp"]*9/5+32))."\n";
	$msg.="WindDirC=".$row["WindDirection"]."\n";
	$msg.="Humidity=".$row["Humidity"]."\n";
	$msg.="AirPressure=".$row["Pressure"]."\n";
	$msg.="Visibility=".$row["Visibility"]."\n";
	$msg.="Icon=".$row["Icon"]."\n";
	$msg.="}\n";
	$msg.="Time\n";
	$msg.="{\n";
	$msg.="Time=".$now."\n";
	$msg.="SunRise=".$sunrise."\n";
	$msg.="SunSet=".$sunset."\n";
	$msg.="TOD=".$timeofday."\n";
	$msg.="}\n";
	
	$subname=preg_replace("/[^a-z0-9]/","",strtolower($row["Location"]));
	xAPSendSub(($id),$subname,"Weather.Report",$msg,"");	
}
}
function CheckIcon($icon){
	//convert names to icon names
	switch ($icon) {
		case "cloudy":
			$icon="cloudy3";break;
		case "clear":
			$icon="sunny";break;
		case "light rain":
			$icon="light_rain";break;
		case "light showers":
			$icon="shower1";break;
		case "sunny intervals":
			$icon="cloudy1";break;
		case "partly cloudy":
			$icon="cloudy2";break;
		case "heavy rain":
			$icon="shower2";break;
		case "foggy":
			$icon="fog";break;
		case "misty":
			$icon="mist";break;
	}


	return $icon;
}
?>